package com.example.ccj.b.c.custom.search;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import com.example.ccj.R;
import com.example.ccj.b.c.custom.MEditTextView;
import com.example.ccj.b.c.custom.MImageView;
import com.example.ccj.b.c.custom.MTextView;
import com.example.ccj.u.KeyboardUtils;


public class SearchView extends LinearLayout {
    public SearchView(Context context) {
        super(context);
        init();
    }

    public SearchView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init(){
        LinearLayout.inflate(getContext(), R.layout.view_search_view,this);
        inPutText = findViewById(R.id.view_search_view_text);
        cancel = findViewById(R.id.view_search_view_cancel);
        deleteText = findViewById(R.id.view_search_view_delete);
    }

    public void show(ISearchListener searchListener){
        inPutText.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) cancel.setVisibility(View.VISIBLE);
                else cancel.setVisibility(View.GONE);
            }
        });

        inPutText.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (searchListener != null) searchListener.onFocusChange(hasFocus,inPutText);
            }
        });

        inPutText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void afterTextChanged(Editable s) {
                if (searchListener != null) searchListener.textChange(inPutText.getText());
                int length = s.toString().trim().length();
                if (length > 0) deleteText.setVisibility(View.VISIBLE);
                else deleteText.setVisibility(View.GONE);
            }
        });

        deleteText.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                inPutText.setText("");
            }
        });

        cancel.setOnClickListener(v -> {
            inPutText.setText("");
            inPutText.clearFocus();
            KeyboardUtils.hideSoftInput(inPutText);
        });
    }

    MEditTextView inPutText;
    MTextView cancel;
    MImageView deleteText;





}
